package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 员工的业务层实现类
 */
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //1.使用用户名查询员工
        Employee employee = employeeMapper.findByUsername(username);
        //2.判断员工是否存在
        if(employee == null){
            return ResultInfo.error("用户不存在！");
        }
        //3.对员工的密码进行加密
        if(StringUtils.isNotEmpty(password)) {
            String md5Password = SecureUtil.md5(password);
            //4.使用加密后的密码和员工的密码进行比较
            if(!md5Password.equals(employee.getPassword())){
                //密码不一致
                return ResultInfo.error("密码有误！");
            }
            //5.判断员工的状态
            if(employee.getStatus() == 1){
                //6.密码匹配成功 返回员工
                return  ResultInfo.success(employee);
            }
        }
        return null;
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
        //补全id主键
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        //补全初始密码
        employee.setPassword(SecureUtil.md5("123456"));
        //补全状态
        employee.setStatus(1);
        /*//补全创建者信息和创建时间
        employee.setCreateUser(1L);
        employee.setCreateTime(new Date());
        //补全更新者信息和更新时间
        employee.setUpdateUser(1L);
        employee.setUpdateTime(new Date());*/
        //返回
        employeeMapper.insert(employee);
    }

    @Override
    public Employee findById(Long id) {
        System.out.println(id);
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
        /*employee.setUpdateTime(new Date());
        employee.setUpdateUser(1L);*/
        employeeMapper.updateById(employee);
    }
}
